package com.example.wangzh.developkit.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;

import androidx.annotation.NonNull;

import com.example.wangzh.developkit.base.MyApplication;

import java.lang.reflect.Method;

/**
 * @author: zhwang37
 * @date: 2021/9/2 15:25
 * @email:zhwang37@iflytek.com
 * @describe:
 */
@SuppressWarnings({"unused", "RedundantSuppression"})
public class PermissionUtils {
    @SuppressLint("StaticFieldLeak")
    private static final Context globalContext = MyApplication.getContext();

    /**
     * Show permissions rationale?
     */
    @SuppressLint("ObsoleteSdkInt")
    public static boolean isShowRationalePermission(Context context, String permission) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return false;

        PackageManager packageManager = context.getPackageManager();
        Class<?> pkManagerClass = packageManager.getClass();
        try {
            Method method = pkManagerClass.getMethod("shouldShowRequestPermissionRationale", String.class);
            if (!method.isAccessible()) method.setAccessible(true);
            return (boolean) method.invoke(packageManager, permission);
        } catch (Exception ignored) {
            return false;
        }
    }

    /**
     * Has always been denied permission.
     */
    public static boolean hasAlwaysDeniedPermission(Context context,
                                                    @NonNull String... deniedPermissions) {
        for (String permission : deniedPermissions) {
            if (!isShowRationalePermission(context, permission)) {
                return true;
            }
        }
        return false;
    }
}